# ========== 第一部分：数据合并 ==========
# 设置工作路径
setwd('D:/Rassignment/ADdata')  # 使用正斜杠避免转义问题

# 加载包并检查安装
if (!require("openxlsx")) install.packages("openxlsx")
if (!require("readr")) install.packages("readr")
library(openxlsx)
library(readr)

# 读取文件 - 统一指定列名处理
file1 <- read.table("ADdata1.txt", header = TRUE, row.names = NULL, check.names = FALSE)
file2 <- read.csv("ADdata2.csv", header = TRUE, row.names = NULL, check.names = FALSE)
file3 <- read.xlsx("ADdata3.xlsx", check.names = FALSE)
file4 <- read.table("ADdata4.txt", sep = "", header = TRUE, row.names = NULL, check.names = FALSE)

# 获取通用ID列名（假设第一列为ID）
id_col <- colnames(file1)[1]

# 逐步合并减少内存占用
merged_data <- merge(file1, file4, by = id_col, all = TRUE)
merged_data <- merge(merged_data, file2, by = id_col, all = TRUE)
merged_data <- merge(merged_data, file3, by = id_col, all = TRUE)

# 输出结果
write.xlsx(merged_data, "merged_data.xlsx")
write_csv(merged_data, "merged_data.csv")
write_tsv(merged_data, "merged_data.txt")

# ========== 第二部分：RNA-seq数据处理 ==========
# 设置新路径
setwd('D:/Rassignment/RNAseq_Data')

# 加载必要包
required_pkgs <- c("SummarizedExperiment", "tidyverse", "RColorBrewer", "airway", "edgeR")
for (pkg in required_pkgs) {
  if (!require(pkg, character.only = TRUE)) {
    BiocManager::install(pkg)
    library(pkg, character.only = TRUE)
  }
}

# 读取数据
clin_inf <- read.csv("clin_inf.csv", header = TRUE, check.names = FALSE)
count <- read.csv("count.csv", header = TRUE, check.names = FALSE, row.names = 1)  # 直接设置行名
exp_inf <- read.csv("exp_inf.csv", header = TRUE, check.names = FALSE)
ID_annotation <- read.csv("ID_annoation.csv", header = TRUE, check.names = FALSE)

# 数据处理流程优化
# 1. 临床与实验信息合并
clin_exp_inf <- merge(clin_inf, exp_inf, by = "样本名称") %>%
  column_to_rownames("样本名称")

# 2. 修正count矩阵列名
clean_colnames <- function(x) {
  x %>% 
    gsub("X(\\d+)$", "PTB\\1", .) %>%  # 处理数字结尾
    gsub("X", "XYA", .) %>%            # 处理非数字开头
    gsub("\\.$", "", .)                # 删除末尾的点
}
colnames(count) <- clean_colnames(colnames(count))

# 3. 基因ID处理
ID_annotation <- ID_annotation %>%
  mutate(gene_id = gsub("\\..*", "", gene_id)) %>%
  distinct(gene_id, .keep_all = TRUE)  # 避免重复基因ID

# 4. 对齐数据
count <- count[, rownames(clin_exp_inf), drop = FALSE]  # 确保样本顺序一致
ID_annotation <- ID_annotation[match(rownames(count), ID_annotation$gene_id), ]

# 5. 构建ExpressionSet
eset <- ExpressionSet(
  assayData = as.matrix(count),
  phenoData = AnnotatedDataFrame(clin_exp_inf),
  featureData = AnnotatedDataFrame(ID_annotation %>% column_to_rownames("gene_id"))
)

# 6. 保存结果
saveRDS(eset, "RNAseq_ExpressionSet.rds")